<?php

namespace api\modules\v1\models\user;

use common\models\CacheKeys;
use common\models\Common;
use common\models\Functions;
use common\models\Patterns;
use common\models\Status;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserBusiness extends \common\models\user\UserBusiness
{

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            [['bank_number', 'bank_name','bank_user','bank_image','business_image','place_image','card_just','card_back','user_name','user_phone','user_place'], 'required','message' => '{attribute}不能为空','on' => 'addEdit'],
            [['true_name','id_card'], 'filter', 'filter' => 'trim','on' => ['addEdit']],
        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'user_name' => '姓名',
            'user_phone' => '手机号',
            'user_place' => '地址',
            'bank_number' => '对公账户',
            'bank_name' => '银行名称',
            'bank_user' => '法人',
            'bank_image' => '对公账户照片',
            'business_image' => '营业执照照片',
            'place_image' => '场地照片',
            'card_just' => '身份证正面',
            'card_back' => '身份证反面',

        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'addEdit' => [
                'user_name',
                'user_phone',
                'user_place',
                'bank_number',
                'bank_name',
                'bank_user',
                'bank_image',
                'business_image',
                'place_image',
                'card_just',
                'card_back',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    public function saveBusiness() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $info = static::getOneByWhere(['user_id'=>$user['id']]);

            CacheKeys::checkFrequency($user['id']);

            $data = [];

            $data = array_merge($data, $this->getSaveData($this->scenario, Yii::$app->request->post()));

            if (!preg_match(Patterns::bankCardNo(), $data['bank_number'])) {
                throw new Exception('银行卡格式不正确');
            }
            if (!preg_match(Patterns::phoneNumber(), $data['user_phone'])) {
                throw new Exception('手机号不正确');
            }
            if(empty($info)){
                //添加
                $data['user_id'] = $user['id'];
                $data['create_time'] = date("Y-m-d H:i:s");
                $data['status'] = Status::COMMON_CHECKING_WAITING;
                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('系统异常，请稍后重新提交！');
                }
            }else{
                if($info['status'] != Status::COMMON_CHECKING_DEFEAT){
                    throw new Exception('驳回之后才能重新提交！');
                }
                $data['status'] = Status::COMMON_CHECKING_WAITING;
                $res = static::updateData($data,['user_id'=>$user['id']]);
                if ($res === false) {
                    throw new Exception('系统异常，请稍后重新提交！');
                }

            }


            $trans->commit();
            return Functions::formatRestAPI(0, '上传成功，等待审核！');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 获取
     * @return array
     */
    public function getInfo() {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $where['user_id'] = $user['id'];

            $info = static::getOneByWhere($where);
            if (empty($info)) {
                throw new Exception('未知信息');
            }
            $info['bank_image'] = Common::getImages($info['bank_image']);
            $info['business_image'] = Common::getImages($info['business_image']);
            $info['place_image'] = Common::getImages($info['place_image']);
            $info['card_just'] = Common::getImages($info['card_just']);
            $info['card_back'] = Common::getImages($info['card_back']);
            $info['status_name'] = Status::COMMON_CHECKING_MAP[$info['status']];

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
